/**
    @brief Module affichage avec gtk, fichier source des callbacks

    @file gtkcallbacks.cpp
    @version 0.1
    @date 2008/11/01

*/
#include <string>

#include "gtkview.h"
#include "txtview.h"
#include "../serializer/serializer.h"

bool GtkView::on_timeout(void)
{
    infobus->com->recv('p', command);
    cout << "Commande reçue: " << command << endl;

    /* un fichier groupes a ete recu :
    charger les donnees et remplacer celles existantes */
    if( command == "ADDEDTOGROUP" )
    {
        Serializer groupLoader("group");
        groupLoader.setFileName("group-files-received");
        groupLoader.open('r');
        if( infobus->_groups() != NULL)
        {
            delete infobus->groups;
        }
        infobus->groups = groupLoader.loadGroup();
        groupLoader.close();

        // s'ajouter au groupe
        infobus->groups->addMember(*infobus->_currentUser());
        // sauvegarder le nouveau fichier groupe
        groupLoader.setFileName("group-files");
        groupLoader.open('w');
        groupLoader.saveGroup(*infobus->groups);
        groupLoader.close();
        // envoyer le nouveau fichier
        infobus->sendGroupToAll();
    }
    if( command == "NEWGROUPFILERECEIVED" )
    {
        Serializer groupLoader("group");
        groupLoader.setFileName("group-files-received");
        groupLoader.open('r');
        if( infobus->_groups() != NULL)
        {
            delete infobus->groups;
        }
        infobus->groups = groupLoader.loadGroup();
        groupLoader.close();
        groupLoader.setFileName("group-files");
        groupLoader.open('w');
        groupLoader.saveGroup(*infobus->groups);
        groupLoader.close();
    }

    return true;
}

void GtkView::on_click_add(void)
{
    Gtk::FileChooserDialog dialog("Please choose a folder", Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
    dialog.set_transient_for(*mainWin);

    //Add response buttons to the dialog:
    dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
    dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);

    int result = dialog.run();

    if (result == Gtk::RESPONSE_OK)
    {
        infobus->indexUserFilesFolder( dialog.get_filename() );
        infobus->setMergeWithCommonFiles(*(infobus->_userFiles()));
        TxtView debugview;
        debugview.printTree(*(infobus->_userFiles()));
        fillTreeView();
    }

    return;
}

void GtkView::on_add_folder(void)
{
    dialog_FileChooser->show();
}

void GtkView::on_add_member(void)
{
    int response_AddMember = dialog_AddMember->run();

    if ( response_AddMember == Gtk::RESPONSE_OK)
    {
        cout << "ok clicked" << endl;
        Gtk::Entry* entry_AddMember;
        refXml->get_widget("entry_AddMember", entry_AddMember);
        std::string host = std::string( entry_AddMember->get_text() );

        std::string response;
        ClientSocket client(host, 2500);
        client >> response;
        cout << "reponse recue" << response << endl;
        client << "ADDEDTOGROUP";
        client >> response;
        if (response=="CMDOK")
        {
            client.sendFile("group-files");
        }
    }
    dialog_AddMember->hide();

    return;
}

void GtkView::on_new_group(void)
{
    int response_NewGroup = dialog_NewGroup->run();

    if (response_NewGroup == Gtk::RESPONSE_OK)
    {
        Gtk::Entry* entry_NewGroup;
        refXml->get_widget("entry_NewGroup", entry_NewGroup);
        std::string text = std::string( entry_NewGroup->get_text() );
        if(infobus->groups != NULL)
        {
            delete infobus->groups;
        }
        infobus->groups = new Group(text);
        (infobus->groups)->addMember(*(infobus->_currentUser()));
        Serializer groupSer("group");
        groupSer.open('w');
        groupSer.saveGroup(*(infobus->groups));
        groupSer.close();

        cout << infobus->_groups()->_name() << endl;
    }
    dialog_NewGroup->hide();

    return;
}

void GtkView::on_join_group(void)
{
    dialog_JoinGroup->show();
}

void GtkView::on_sync_files(void)
{
//    int response_Sync_Files = dialog_SyncFiles->run();
//
//    if(response_Sync_Files == Gtk::RESPONSE_OK)
//    {
        infobus->getFileIndexFromAll();
        fillTreeView();

}

void GtkView::on_sync_contacts(void)
{
    infobus->showGroup();
}

void GtkView::on_about(void)
{
    dialog_About->show();
}

void GtkView::on_about_quit(int response)
{
    dialog_About->hide();
}

void GtkView::on_quit(void)
{
    mainWin->hide();
}

//void GtkView::on_treeview_row_expanded(const Gtk::TreeModel::iterator& iter, const Gtk::TreeModel::Path& path)
void GtkView::on_treeview_row_selected(void)
{

    Gtk::TreeModel::iterator iter = refTreeSelection->get_selected();

    if(iter) //If anything is selected
        {
            //Do something with the row: Gtk::TreeModel::Row row = *iter;

    Gtk::TreeModel::Row newrow, treerow;
    Gtk::TreeModel::iterator childiter, rowchildren;
    Gtk::TreeModel::Path childpath;

    childpath = mRefTreeModel->get_path(iter);
    childpath.down();
    childiter = mRefTreeModel->get_iter(childpath);
    treerow = *childiter;
    rowchildren = treerow.children();

    mRefListModel->clear();

    while (rowchildren)
    {
        treerow = *rowchildren;

        if (treerow.get_value(mColumns.type_col)=="file")
        {
            newrow = *(mRefListModel->append());
            newrow[mColumns.name_col] = treerow.get_value(mColumns.name_col);
            newrow[mColumns.path_col] = treerow.get_value(mColumns.path_col);
            newrow[mColumns.owner_col] = treerow.get_value(mColumns.owner_col);
            newrow[mColumns.host_col] = treerow.get_value(mColumns.host_col);
            newrow[mColumns.type_col] = treerow.get_value(mColumns.type_col);
            newrow[mColumns.icon_col] = treerow.get_value(mColumns.icon_col);
        }

        rowchildren++;
    }
        }
}

/*
void GtkView::on_treeview_selected_foreach( const Gtk::TreeModel::Path& path )
{
    Glib::RefPtr<Gtk::TreeSelection> refTreeSelection = mTreeView->get_selection();

    Gtk::TreeModel::iterator iter = refTreeSelection->get_selected();
    if(iter) //If anything is selected
        {
            Gtk::TreeModel::Row row = *iter;
            //Do something with the row.
        }

}
*/

void GtkView::on_iconview_item_activated( const Gtk::TreeModel::Path& path )
{
    Gtk::TreeModel::iterator iter = mRefListModel->get_iter(path);
    if(iter)
    {
        Gtk::TreeModel::Row row = *iter;
        infobus->getFile(row.get_value(mColumns.host_col), 2500,
                        row.get_value(mColumns.path_col),
                        row.get_value(mColumns.name_col) );
    }
}

//void GtkView::on_iconview_selected_foreach( const Gtk::TreeModel::Path& path )
void GtkView::on_iconview_selected_foreach( void )
{
    /* Signal connection debug */
    cout << "selection changed" << endl;

    Gtk::IconView::ArrayHandle_TreePaths select = mIconView->get_selected_items();
    cout << "got selection" << endl;

    if (!select.empty())
    {
    Gtk::TreeModel::iterator iter = mRefListModel->get_iter(*(select.begin()));
    cout << "if you get a segfault now, you got a problem with the ArrayHandle" << endl;

    if(iter)
    {
        Gtk::TreeModel::Row row = *iter;

        entry_MainWinFileInfoName->set_label(row.get_value(mColumns.name_col) );
        entry_MainWinFileInfoOwner->set_label(row.get_value(mColumns.owner_col) );
        entry_MainWinFileInfoType->set_label(row.get_value(mColumns.type_col) );
        // debug
        cout << row[mColumns.name_col] << " - " << row[mColumns.owner_col] << " - " << row[mColumns.type_col] << endl;
    }
    }
}
